package com.example.test.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.test.common.P;
import com.example.test.domain.Book;
import com.example.test.domain.Empoyee;
import com.example.test.service.Bookservice;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private Bookservice bookservice;
    @PostMapping("/getallbook")
    public P<List<Book>> getallbook(){
        List<Book> list = bookservice.list();
        return P.success(list);
    }
    @PostMapping("/deletebook")
    public P<String> deletebook(@RequestBody Book book){
        boolean b = bookservice.removeById(book.getBookid());
        if(b){
            return P.success("删除成功！");
        }
        return P.error("删除失败");
    }
    @PostMapping("/updatebook")
    public P<String> updatebook(@RequestBody Book book){
        if(book.getBookid()==-1){//说明是新增
            book.setHaiyou(book.getNumber());
            book.setBookid(0);
            bookservice.save(book);
            return P.success("新增成功");
        }
        LambdaQueryWrapper<Book> wrapper=new LambdaQueryWrapper();
        wrapper.eq(Book::getBookid,book.getBookid());
        Book one = bookservice.getOne(wrapper);

        one.setHaiyou(one.getHaiyou()+(book.getNumber()-one.getNumber()));
        one.setNumber(book.getNumber());
        one.setBookname(book.getBookname());
        bookservice.updateById(one);
        return P.success("修改成功");
    }
    @PostMapping("/search")
    public P<List<Book>> search(@RequestBody Book book){
//        System.out.println(book);
        LambdaQueryWrapper<Book> wrapper=new LambdaQueryWrapper<>();
        wrapper.like(Book::getBookname,book.getBookname());
        List<Book> list = bookservice.list(wrapper);
        return P.success(list);
    }
    @GetMapping("/page")
    public P<List<Book>> page(int page,String name){
//        System.out.println(page+name);
        //分页构造器
        Page<Book> pageInfo=new Page(page,10);
        //name可能传，可能不传
        LambdaQueryWrapper<Book> wrapper=new LambdaQueryWrapper();
        //过滤
        wrapper.like(name!=null,Book::getBookname,name);
        //查询
        List<Book> list = bookservice.page(pageInfo, wrapper).getRecords();
        return P.success(list);
    }
}
